package cn.com.dcsgo.security;

import cn.com.dcsgo.constant.RedisConst;
import cn.com.dcsgo.util.jwt.JwtHelper;
import cn.com.dcsgo.vo.user.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 *
 * @author Dcsgo
 * @since 2025/4/24 15:07
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {
    private final RedisTemplate<Object, Object> redisTemplate;

    public UserLoginInterceptor(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 前置拦截，根据 token 将用户信息添加到 AuthContextHolder 中
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return true
     * @throws Exception Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initAuthContextHolder(request);
        return true;
    }

    /**
     * 根据 token 将用户信息添加到 AuthContextHolder 中
     *
     * @param request request
     */
    private void initAuthContextHolder(HttpServletRequest request) {
        String token = request.getHeader("token");
        log.debug("token:" + token);
        if (!StringUtils.isEmpty(token)) {
            Long userId = JwtHelper.getUserId(token);
            AuthContextHolder.setUserId(userId);
            log.debug("JwtHelper.getUserId() userId:" + userId);
            UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);
            log.debug("userLoginVo:" + userLoginVo);
            if (userLoginVo != null) {
                AuthContextHolder.setUserLoginVo(userLoginVo);
                AuthContextHolder.setWareId(userLoginVo.getWareId());
            }
        }
    }
}
